{
 "cells": [
  {
   "cell_type": "markdown",
   "source": [
    "## ChatCompletion API实践之多轮对话机器人"
   ],
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "本章主要利用ChatCompletion API的使用技巧，以及message参数中system可以实现知识背景的设置；\n",
    "让大模型浏览本地知识库内容，将其设定为System role的知识背景，实现一个多轮对话机器人的案例"
   ],
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "1.初步测试\n",
    "咨询大模型一个未经训练不知道的内容"
   ],
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "outputs": [],
   "source": [
    "from openai import OpenAI\n",
    "client = OpenAI()\n",
    "response = client.chat.completions.create(\n",
    "  model=\"gpt-3.5-turbo\",\n",
    "  messages=[\n",
    "    {\"role\": \"system\", \"content\": \"null\"},\n",
    "    {\"role\": \"user\", \"content\": '你知道《地球特派员》的电影里角色有哪些吗？'}\n",
    "  ]\n",
    ")"
   ],
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "outputs": [
    {
     "data": {
      "text/plain": "'《地球特派员》是一部动画电影，也称为《Men in Black》。以下是电影中的一些角色：\\n\\n1. Agent K (凯)\\n2. Agent J (杰)\\n3. Frank the Pug (弗兰克)\\n4. Agent L (艾丽)\\n5. Zed (齐德)\\n6. Edgar the Bug (埃德加)\\n7. Laurel Weaver (劳瑞）\\n8. Serleena (赛琳娜)\\n\\n这些是电影中比较重要的主要角色，还有其他一些次要角色和外星人角色。'"
     },
     "execution_count": 18,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "response.choices[0].message.content"
   ],
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "2.读取本地知识库\n",
    "读取本地服务器提前准备好的知识库内容"
   ],
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "outputs": [],
   "source": [
    "with open('地球特派员.txt', 'r', encoding='utf-8') as f:\n",
    "    chatCompletion_kg = f.read()"
   ],
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "outputs": [
    {
     "data": {
      "text/plain": "'电影：地球特派员 Elio\\n导演: 阿德里安·莫利纳\\n主演: 约纳斯·基布雷亚布 / 亚美莉卡·费雷拉\\n类型: 喜剧 / 科幻 / 动画 / 冒险\\n上映日期: 2024-03-01(美国)\\n这是皮克斯宣布了第 28 部故事片，将聚焦于一个 11 岁的男孩（当然叫 Elio），他无意中被传送到太空，被误认为是另一个星球上的地球大使。'"
     },
     "execution_count": 20,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "chatCompletion_kg"
   ],
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "3.问答测试\n",
    "以本地知识库作为背景知识，让大模型回答相关问题"
   ],
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "outputs": [],
   "source": [
    "response = client.chat.completions.create(\n",
    "  model=\"gpt-3.5-turbo\",\n",
    "  messages=[\n",
    "    {\"role\": \"system\", \"content\": chatCompletion_kg},\n",
    "    {\"role\": \"user\", \"content\": '你知道《地球特派员》的电影里角色有哪些吗？'}\n",
    "  ]\n",
    ")"
   ],
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "outputs": [
    {
     "data": {
      "text/plain": "'当然！《地球特派员》电影中的主要角色包括：\\n\\n1. Elio：主角，一个 11 岁的男孩，被误认为是地球大使而被传送到另一个星球上。\\n2. 太空探险家 Zara：另一个星球的居民，是 Elio 在外太空中遇到的重要角色。\\n3. 机器人小助手 R1C4：协助 Elio 在另一个星球上生存和应对挑战的机器人伙伴。\\n4. 地球特派员团队：一群来自不同星球的使者，与 Elio 一起合作展开冒险活动。\\n\\n这些角色将在影片中展开一系列有趣、惊险和感人的故事情节。'"
     },
     "execution_count": 22,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "response.choices[0].message.content"
   ],
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "4.实现多轮对话\n",
    "\n",
    "利用本地知识库+循环处理实现简单的多轮对话效果"
   ],
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "outputs": [],
   "source": [
    "def chat_with_model(messages):\n",
    "    response = client.chat.completions.create(\n",
    "        model=\"gpt-3.5-turbo\",\n",
    "        messages=messages\n",
    "    )\n",
    "    return response.choices[0].message.content\n",
    "\n",
    "# 测试函数\n",
    "def gpt_chat_with_model():\n",
    "    # 初始问候\n",
    "    messages = [\n",
    "        {\"role\": \"system\", \"content\": chatCompletion_kg}, ##添加本地知识库\n",
    "        {\"role\": \"user\", \"content\": \"你好！\"},\n",
    "        {\"role\": \"assistant\", \"content\": \"你好！我是一个AIGC智能助理，有什么问题我可以帮助你？\"}\n",
    "    ]\n",
    "    print(chat_with_model(messages))\n",
    "\n",
    "    # 进行对话\n",
    "    while True:\n",
    "        user_input = input(\"用户：\")\n",
    "        messages.append({\"role\": \"user\", \"content\": user_input})\n",
    "        assistant_response = chat_with_model(messages)\n",
    "        messages.append({\"role\": \"assistant\", \"content\": assistant_response})\n",
    "        print(\"助理：\" + assistant_response)\n",
    "\n",
    "        # 判断是否结束对话\n",
    "        if user_input.lower() == 'quit':\n",
    "            break"
   ],
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "code",
   "execution_count": 25,
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "电影《地球特派员 Elio》讲述了一个11岁男孩被误认为是地球大使的故事。你喜欢看这类喜剧、科幻和冒险题材的电影吗？\n",
      "助理：这部电影的导演是阿德里安·莫利纳（Adrian Molina）。\n",
      "助理：《地球特派员》的主演包括约纳斯·基布雷亚布（Jonas Kühnemann）和亚美莉卡·费雷拉（Amarilys Ferreira）。\n",
      "助理：《地球特派员》预计于2024年3月1日在美国上映。\n",
      "助理：《地球特派员》是一部喜剧、科幻、动画和冒险题材相结合的电影。\n",
      "助理：如有任何其他问题，欢迎随时向我提问！祝您有美好的一天！如果需要帮助，请随时回来。再见！\n"
     ]
    }
   ],
   "source": [
    "gpt_chat_with_model()"
   ],
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "outputs": [],
   "source": [],
   "metadata": {
    "collapsed": false
   }
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 0
}
